package com.lujianfei.android_app_list

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lujianfei.android_app_list.adapter.GridAdapter
import com.lujianfei.android_app_list.base.BaseFragment
import com.lujianfei.android_app_list.utils.AppHelper
import com.lujianfei.android_app_list.utils.DensityHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class AppGridFragment : BaseFragment() {

    private var recyclerview: RecyclerView? = null
    private var loading: View? = null
    private val mAdapter by lazy { GridAdapter() }
    override fun resourceId(): Int = R.layout.fragment_app_grid

    override fun initView() {
        recyclerview = findViewById(R.id.recyclerview)
        loading = findViewById(R.id.loading)
        recyclerview?.apply {
            layoutManager = GridLayoutManager(context,3)
            addItemDecoration(ItemMargin())
        }
    }

    override fun initData() {
        launchOnUI {
            val appList = withContext(Dispatchers.IO) {
                AppHelper.getAppList()
            }
            mAdapter.setData(appList)
            recyclerview?.adapter = mAdapter
            loading?.visibility = View.GONE
        }
    }

    override fun initEvent() {
        mAdapter.onItemClickListener = {
            startActivity(MyApplication.INSTANCE.packageManager.getLaunchIntentForPackage(it.packageName))
        }
    }

    class ItemMargin: RecyclerView.ItemDecoration() {
        override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
            super.getItemOffsets(outRect, view, parent, state)
            outRect.top = DensityHelper.dip2px(20f)
        }
    }
}